<?php

namespace app\app\controller;
use think\Db;

class Express extends Common
{
    //配送员获取抢单，订单列表
    public function order_list()
    {
        $uid = token_decode(req('token'));
        $status = req('type');
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid) || empty($status)) {
            $msg['msg'] = '参数错误';
        } else {
            if ($status != 2 && $status != 3 && $status != 4 && $status != 5) {
                $msg['msg'] = '非法操作';
            } else {
                $where['status'] = $status;
            }
        }
        $express = Db::table('express')->where('id',$uid)->find();
        $where['aid'] = $express['aid'];
        $page = !empty(req('page')) ? req('page') : 1;
        $pagesize = !empty(req('pagesize')) ? req('pagesize') : 10;
        $fields = 'order_id,seller_id,name,address,phone,last_price as price,remark,express_charge,status,seller_order_id,lng,lat';
        $msg['count'] = Db::table('order')->where($where)->count();
        if ($status == 2) {
            $where['advance_receive'] = 1;
            $data = Db::table('order')->field($fields)->where($where)->page($page, $pagesize)->order('status asc,time desc')->select();
        } else {
            $where['express_id'] = $uid;
            $data = Db::table('order')->field($fields)->where($where)->page($page, $pagesize)->order('status asc,time desc')->select();
        }
        $msg['state'] = 1;
        foreach ($data as $k => $v) {
            // $cut = Db::table('express')->where('id', $uid)->value('cut');
            // $data[$k]['express_charge'] = (string)round($v['express_charge'] - ($v['express_charge'] * ($cut / 100)), 2);
            $seller = Db::table('seller')->where('id', $v['seller_id'])->find();
            $goods_number = 0;
            $data[$k]['goods'] = Db::table('order_detail')->where(['order_id' => $v['order_id']])->select();
            $data[$k]['goods_number'] = $goods_number;
            $data[$k]['seller'] = $seller['name'];
            $data[$k]['seller_phone'] = $seller['phone'];
            $data[$k]['seller_address'] = $seller['address'];
            $data[$k]['seller_lng'] = strval($seller['lng']);
            $data[$k]['seller_lat'] = strval($seller['lat']);
        }
        $msg['data'] = $data;
        $msg['msg'] = '获取成功';
        return json($msg);
    }

    //配送员操作订单
    public function order_set()
    {
        $uid = token_decode(req('token'));
        $order_id = req('order_id');
        $status = req('status');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($order_id) || empty($status)) {
            $msg['msg'] = '参数错误';
        } else {
            if ($status != 3 && $status != 4 && $status != 5) {
                $msg['msg'] = '非法操作';
            } else {
                $order = Db::table('order')->where('order_id', $order_id)->find();
                if (($status - 1) != $order['status']) {
                    $msg['msg'] = '非法操作';
                } else {
                    $msg['state'] = 1;
                    if ($status == 3) {
                        // $cut = Db::table('express')->where('id', $uid)->value('cut');
                        // $update['express_charge'] = strval(round($order['express_charge'] - ($order['express_charge'] * ($cut / 100)), 2));
                        $update['express_id'] = $uid;
                        $update['express_receive_time'] = time();

                        push(md5($order['uid']), json_encode(['type' => 2, 'message' => '您的订单已被配送员接单', 'parameters' => $order_id]), 'user');
                        push(md5($order['seller_id']), json_encode(['type' => 2, 'message' => '您的订单已被配送员接单,请等待配送员上门取货', 'parameters' => $order_id]), 'seller');
                    } elseif ($status == 4) {
                        $update['express_time'] = time();

                        //push用户
                        push(md5($order['uid']), json_encode(['type' => 2, 'message' => '您的订单已被配送员送出', 'parameters' => $order_id]), 'user');
                    } elseif ($status == 5) {
                        //完成订单
                        $update['complete_time'] = time();

                        //给商家和配送员加钱
                        $seller = Db::table('seller')->field('cut,aid,volume,comode')->where('id', $order['seller_id'])->find();
												if($seller['comode'] == 0){
													if(!empty($order['money_off'])){
														$order['goods_price'] = $order['goods_price'] - $order['seller_money_off'];
													}
													$order['goods_price'] = $order['goods_price'] + $order['box_charge'];
													$seller_money = $order['goods_price'] - ($order['goods_price'] * $seller['cut'] / 100);
																		}else{
													$order['goods_price'] = $order['goods_price'] + $order['box_charge'];
													$seller_money = $order['goods_price'] - ($order['goods_price'] * $seller['cut'] / 100);
													if(!empty($order['money_off'])){
														$order['goods_price'] = $order['goods_price'] - $order['seller_money_off'];
													}
												}
												$seller_money = round($seller_money,2);
                        Db::table('seller')->where('id', $order['seller_id'])->setInc('money', $seller_money);
                        Db::table('earning')->insert(['order_id' => $order_id, 'uid' => $order['seller_id'], 'money' => $seller_money, 'time' => time(), 'type' => 'seller']);

                        $express = Db::table('express')->where('id', $uid)->find();
                        $express_money = $order['express_charge'] - ($order['express_charge'] * $express['cut'] / 100);
                        Db::table('express')->where('id', $uid)->setInc('money', $express_money);
                        Db::table('earning')->insert(['order_id' => $order_id, 'uid' => $uid, 'money' => $order['express_charge'], 'time' => time(), 'type' => 'express']);

                        //push用户
                        push(md5($order['uid']), json_encode(['type' => 2, 'message' => '您的订单已完成', 'parameters' => $order_id]), 'user');

                        //自动评价预启动
                        Db::table('evaluate')->insert(['order_id'=>$order_id,'seller_id'=>$order['seller_id'],'uid'=>$order['uid'],'star'=>'5.0','text'=>'系统默认好评','time'=>time(),'complete_time'=>time()]);
                        Db::table('evaluate')->insert(['order_id'=>$order_id,'express_id'=>$uid,'uid'=>$order['uid'],'star'=>'5.0','text'=>'系统默认好评','time'=>time(),'complete_time'=>time()]);

                        //push商家
                        push(md5($order['seller_id']), json_encode(['type' => 2, 'message' => '订单已完成，本次收益'.$seller_money.'元', 'parameters' => $order_id]), 'seller');

                        //销量
                        $volume = $seller['volume'];
                        $goods = Db::table('order_detail')->where('order_id', $order['order_id'])->select();
                        foreach ($goods as $k => $v) {
                            $volume += $v['number'];
                            $goods_volume = (int)Db::table('service')->where('id',$v['goods_id'])->value('volume');
                            Db::table('service')->where(['id' => $v['goods_id'], 'uid' => $v['seller_id']])->update(['volume'=> $goods_volume+$v['number'],'volume_date'=>date('Ym')]);
                        }
                        Db::table('seller')->where('id',$order['seller_id'])->update(['volume'=>$volume,'volume_date'=>date('Ym')]);

                        //推送新单给自己
                        $new_order_count = Db::table('order')->where(['order_id'=>['<>',$order_id],'status'=>2,'advance_receive'=>1,'aid'=>$seller['aid']])->count();
                        $oneself_order = Db::table('order')->where(['order_id'=>['<>',$order_id],'express_id'=>$uid,'status'=>['between','2,4']])->count();
                        if($new_order_count > 0 && $oneself_order == 0){
                            push(md5($uid),json_encode(['type' => 5, 'message' => '有新的订单可以抢单哦~', 'parameters' =>'']),'express');
                        }
												
												$user_order_count = Db::table('order')->where(['order_id'=>['<>',$order_id],'uid'=>$order['uid'],'status'=>5])->count();
												$invitation = Db::table('user')->where(['id'=>$order['uid'],'status'=>1])->value('invite');
												//邀请送好礼
												if (!empty($invitation) && $user_order_count == 0) {
													$where['aid'] = $order['aid'];
													$where['status'] = 1;
													$where['title'] = '邀请送好礼';
													$active = Db::table('active')->where($where)->find();
													if (!empty($active['redpacket'])) {
														$this->grant_redpacket($invitation,$active['redpacket'],'邀请红包',0);
													}
												}
												//三级分销
												$setting = Db::table("setting")->where(['id'=>1])->find();
												//一级
												if(!empty($invitation) && $setting['level_1']>0){
													$commision_money = round($order['last_price']/100*$setting['level_1'],2);
													if(Db::table("user")->where(['id'=>$invitation,'status'=>1])->setInc('money', $commision_money)){
														Db::table('earning')->insert(['order_id' => $order_id, 'uid' => $invitation, 'money' => $commision_money, 'time' => time(), 'type' => 'user']);
														$commision = $commision + $commision_money;
													}
													//二级
													if(!empty($invitation) && $setting['level_2']>0){
														$invitation = Db::table('user')->where(['id'=>$invitation,'status'=>1])->value('invite');
														$commision_money = round($order['last_price']/100*$setting['level_2'],2);
														if(Db::table("user")->where(['id'=>$invitation,'status'=>1])->setInc('money', $commision_money)){
															Db::table('earning')->insert(['order_id' => $order_id, 'uid' => $invitation, 'money' => $commision_money, 'time' => time(), 'type' => 'user']);
															$commision = $commision + $commision_money;
															//三级
															if(!empty($invitation) && $setting['level_3']>0){
																$invitation = Db::table('user')->where(['id'=>$invitation,'status'=>1])->value('invite');
																$commision_money = round($order['last_price']/100*$setting['level_3'],2);
																if(Db::table("user")->where(['id'=>$invitation,'status'=>1])->setInc('money', $commision_money)){
																	Db::table('earning')->insert(['order_id' => $order_id, 'uid' => $invitation, 'money' => $commision_money, 'time' => time(), 'type' => 'user']);
																	$commision = $commision + $commision_money;
																}
															}
														}
													}
												}
												//算平台钱+不算配送费
                        //$update['system_money'] = $order['last_price']-$seller_money-$express_money;
                        $update['system_money'] = $order['last_price']-$seller_money-$commision;
                    }
                    $update['status'] = $status;
                    Db::table('order')->where('order_id', $order_id)->update($update);
                    $msg['msg'] = '操作成功';
                }
            }
        }
        return json($msg);
    }

    //配送员获取个人信息
    public function get_info()
    {
        $uid = token_decode(req('token'));
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $data = Db::table('express')->field('headimg,name,phone')->where('id', $uid)->find();
            $msg['data'] = $data;
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

    //配送员获取订单量
    public function order_count()
    {
        $uid = token_decode(req('token'));
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $data = [];

            //当日
            $start_time = strtotime(date('Y-m-d 00:00:00'));
            $stop_time = strtotime(date('Y-m-d 23:59:59'));
            $data['today_order'] = Db::table('earning')->where(['uid' => $uid, 'time' => ['between',$start_time.','.$stop_time], 'type' => 'express'])->count();

            //本月
            $start_time = strtotime(date('Y-m-01 00:00:00'));
            $stop_time = strtotime(date('Y-m-d', strtotime('+1 months', $start_time)));
            $data['month_order'] = Db::table('earning')->where(['uid' => $uid, 'time' => ['between',$start_time.','.$stop_time], 'type' => 'express'])->count();

            //累计
            $data['total_order'] = Db::table('earning')->where(['uid'=>$uid, 'type' => 'express'])->count();

            $msg['data'] = $data;
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

    public function losemoney()
    {
        $token = req('token');
        $uid = token_decode($token);
        $user = Db::table('express')->where('id', $uid)->find();
        $money = $user['money'];
        $msg['state'] = 0;
        $msg['data'] = '';
        if ($user['money'] < $money || $money < 100) {
            $msg['msg'] = '很抱歉，您的余额不满足提现条件';
        } else {
            if ($user['losemoney'] != 0) {
                $msg['msg'] = '您上一个提现处理还未完成，无法再进行提现';
            } else {
                $post['uid'] = $uid;
                $post['status'] = 2;
                $post['type'] = 'express';
                $post['truename'] = $user['name'];
                $post['account'] = $user['bank_card'];
                $post['money'] = $user['money'];
                $post['lose_time'] = time();
                Db::table('losemoney')->insert($post);
                Db::table('express')->where('id', $uid)->update(['money' => $user['money'] - $money, 'losemoney' => $money]);
                $msg['state'] = 1;
                $msg['msg'] = '提现申请成功';
            }
        }
        return json($msg);
    }

    public function lose_info()
    {
        $token = req('token');
        $uid = token_decode($token);
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $msg['msg'] = '获取成功';
            $msg['count'] = Db::table('losemoney')->where(['uid' => $uid, 'type' => 'express'])->count();
            $fields = 'money,status,lose_time as losttime';
            $page = !empty(req('page')) ? req('page') : 1;
            $pagesize = !empty(req('pagesize')) ? req('pagesize') : 10;
            $msg['data'] = Db::table('losemoney')->field($fields)->where(['uid' => $uid, 'type' => 'express'])->page($page, $pagesize)->order('lose_time desc')->select();
        }
        return json($msg);
    }

    public function earning_detail()
    {
        $token = req('token');
        $uid = token_decode($token);
        $msg['state'] = 0;
        $msg['data'] = [];
        if (empty($uid)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            $msg['count'] = Db::table('earning')->where(['uid' => $uid, 'type' => 'express'])->count();
            $page = !empty(req('page')) ? req('page') : 1;
            $pagesize = !empty(req('pagesize')) ? req('pagesize') : 10;
            $msg['data'] = Db::table('earning')->field('order_id,money,time')->where(['uid' => $uid, 'type' => 'express'])->page($page, $pagesize)->order('time desc')->select();
            $msg['msg'] = '获取成功';
        }
        return json($msg);
    }

    public function upload_address()
    {
        $uid = token_decode(req('token'));
        $lng = req('lng');
        $lat = req('lat');
        $msg['state'] = 0;
        $msg['data'] = '';
        if (empty($uid) || empty($lng) || empty($lat)) {
            $msg['msg'] = '参数错误';
        } else {
            $msg['state'] = 1;
            Db::table('express')->where('id', $uid)->update(['lng' => $lng, 'lat' => $lat,'active_time'=>time()]);
            $msg['msg'] = '操作成功';
        }
        return json($msg);
    }

    public function get_address()
    {
        $express_id = req('express_id');
        $data = Db::table('express')->field('lng,lat')->where('id',$express_id)->find();
        return json(['state'=>1,'data'=>$data,'msg'=>'获取成功']);
    }

    public function get_evaluate_list()
    {
        $uid = token_decode(req('token'));
        $star = req('star');
        $page = req('page') ? req('page') : 1;
        $page_size = req('page_size') ? req('page_size') : 10;
        $where['express_id'] = $uid;
        $where['type'] = 'express';
        if(!empty($star)){
            $where['star'] = $star;
        }
        $data = Db::table('evaluate')->field('uid,star,text,image1,image2,time')->where($where)->where('time>complete_time or complete_time<=' . time() - 30000)->page($page, $page_size)->select();
        foreach ($data as $index => $datum) {
            unset($data[$index]['uid']);
            $user = Db::table('user')->field('headimg,name')->where('id', $datum['uid'])->find();
            $data[$index] = array_merge($data[$index], $user);
        }
        return json(['state' => 1, 'data' => $data, 'msg' => '获取成功']);
    }

}